package com.lishilin.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lishilin.common.constant.ProductConstant;
import com.lishilin.common.to.SkuReductionTo;
import com.lishilin.common.to.SpuBoundsTo;
import com.lishilin.common.to.es.SkuEsModel;
import com.lishilin.common.utils.R;
import com.lishilin.gulimall.product.dao.SpuInfoDescDao;
import com.lishilin.gulimall.product.entity.*;
import com.lishilin.gulimall.product.feign.CouponFeignService;
import com.lishilin.gulimall.product.feign.SearchFeignService;
import com.lishilin.gulimall.product.feign.WareFeignService;
import com.lishilin.gulimall.product.service.*;
import com.lishilin.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lishilin.common.utils.PageUtils;
import com.lishilin.common.utils.Query;

import com.lishilin.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService saleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //因为前面调用了basespuinfo的保存方法 会自动生成主键，所有可以拿到spuid
        spuInfoDescEntity.setSpuId(infoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //3.保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(infoEntity.getId(),images);
        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(infoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            //根据attrid查询出attr的属性名
            AttrEntity attrentit = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrentit.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);
        //5.保存spu的积分信息；gulimall_sms->sms_spu_bounds
        //将积分保存到gulimall—coupon服务中的spuboundscontroller所指定的表中  使用远程调用feign功能
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode()!=0) {
            log.error("远程保存spu积分信息失败");
        }

        //5.保存当前spu对应的所有sku信息
        //5.1 sku的基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus!=null&&skus.size()>0){
            skus.forEach(sku->{
                String deaultImg="";
                for (Images image:sku.getImages()) {
                    if (image.getDefaultImg()==1){
                        deaultImg=image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(deaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
        //5.2 sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();//上面sku信息保存完毕之后就会生成skuid可以用于保存sku_images
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    // TODO: 2022/03/05 没有图片路径的无须保存
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                //5.3 sku的销售属性信息  pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attr1 -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr1, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                saleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //5.4 sku的优惠满减等信息 gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //如果满减信息没有的时候就不需要发送远程请求
                if (skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode()!=0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }





    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * status:
         * key:
         * brandId: 0
         * catelogId: 0
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(spuInfoEntityQueryWrapper->spuInfoEntityQueryWrapper.eq("id",key).or().like("spu_name",key));
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)&&!"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)&&!"0".equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }



    @Transactional
    @Override
    public void up(Long spuId) {
        //组装需要的数据
        //1.查出当前spuid丢应的所有sku信息、品牌名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查询当前sku所有可以被检索的规格属性，当前sku的属性是集成与spu的 所以可以通过spuid查询出规格属性
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = attrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrsIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> searchAttrValues = attrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item,attrs);
            return attrs;
        }).collect(Collectors.toList());

        //发送远程调用hasstock查询库存  ware系统是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            stockMap = skusHasStock.getData(new TypeReference<List<SkuHasStockVo>>(){}).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e) {
            log.error("库存服务查询异常，原因{}",e);
        }
        //2.封装没个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProdects = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);
            //skuPrice,skuImg,hasstock,hoscore,brandName,brandImg,attrs
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //设置是否有库存
            if (finalStockMap ==null) {
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //热度评分  0
            skuEsModel.setHotScore(0L);
            //查询品牌和分类名
            BrandEntity brandentity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandentity.getName());
            skuEsModel.setBrandImg(brandentity.getLogo());
            CategoryEntity categoryentity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryentity.getName());
            //设置检索规格属性
            skuEsModel.setAttrs(searchAttrValues);


            return skuEsModel;
        }).collect(Collectors.toList());

        //将数据发送给es进行保存
        R r = searchFeignService.prodectStatusUp(upProdects);
        if (r.getCode()==0) {
            //远程调用成功
            //修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            // TODO: 2022/03/08 重复调用？接口幂等性
            //1.构造请求数据，将数据转为json
            //2.发送数据进行执行（执行成功会解码响应数据）
            //3.执行请求有重试机制

        }
    }


}